// pages/edit/edit.js
Page({
  data: {
    originalImage: '',
    selectedSize: '一寸',
    selectedColor: '蓝色',
    watermarkEnabled: false,
    watermarkText: '',
    isProcessing: false,
    resultImages: [],
    showSizeAction: false,
    showColorAction: false,
    sizeOptions: [
      '一寸',
      '二寸', 
      '小一寸',
      '小二寸',
      '大一寸',
      '大二寸',
      '五寸',
      '教师资格证',
      '国家公务员考试',
      '初级会计考试',
      '英语四六级考试',
      '计算机等级考试',
      '研究生考试',
      '社保卡',
      '电子驾驶证',
      '美国签证',
      '日本签证',
      '韩国签证'
    ],
    colorOptions: [
      '蓝色',
      '白色',
      '红色',
      '黑色'
    ]
  },

  onLoad() {
    // 检查登录状态
    const openid = wx.getStorageSync('openid')
    if (!openid) {
      wx.redirectTo({
        url: '/pages/login/login'
      })
    }
  },

  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        this.setData({
          originalImage: res.tempFiles[0].tempFilePath,
          resultImages: []
        })
      },
      fail: () => {
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },

  showSizePicker() {
    this.setData({ showSizeAction: true })
  },

  onSizeClose() {
    this.setData({ showSizeAction: false })
  },

  onSizeSelected(e) {
    console.log('尺寸选择器返回:', e.detail);
    let selectedValue = '';
    
    if (e.detail && typeof e.detail === 'object' && e.detail.selected) {
      selectedValue = e.detail.selected;
    } else if (typeof e.detail === 'string') {
      selectedValue = e.detail;
    } else {
      selectedValue = String(e.detail || '');
    }
    
    if (selectedValue) {
      this.setData({
        selectedSize: selectedValue,
        showSizeAction: false
      })
    } else {
      console.warn('尺寸选择器返回了无效值:', e.detail);
      this.setData({ showSizeAction: false });
    }
  },

  showColorPicker() {
    this.setData({ showColorAction: true })
  },

  onColorClose() {
    this.setData({ showColorAction: false })
  },

  onColorSelected(e) {
    console.log('颜色选择器返回:', e.detail);
    let selectedValue = '';
    
    if (e.detail && typeof e.detail === 'object' && e.detail.selected) {
      selectedValue = e.detail.selected;
    } else if (typeof e.detail === 'string') {
      selectedValue = e.detail;
    } else {
      selectedValue = String(e.detail || '');
    }
    
    if (selectedValue) {
      this.setData({
        selectedColor: selectedValue,
        showColorAction: false
      })
    } else {
      console.warn('颜色选择器返回了无效值:', e.detail);
      this.setData({ showColorAction: false });
    }
  },

  toggleWatermark(e) {
    this.setData({
      watermarkEnabled: e.detail.value
    })
  },

  onWatermarkTextChange(e) {
    this.setData({
      watermarkText: e.detail.value
    })
  },

  async processImage() {
    if (!this.data.originalImage) {
      wx.showToast({
        title: '请先选择图片',
        icon: 'none'
      })
      return
    }

    this.setData({ isProcessing: true })

    try {
      const openid = wx.getStorageSync('openid')
      
      const app = getApp();
      const apiUrl = app.globalData.api_url;
      
      // 上传图片到后端
      const uploadTask = wx.uploadFile({
        url: apiUrl + 'api/idphoto/process',
        filePath: this.data.originalImage,
        name: 'file',
        formData: {
          size_name: this.data.selectedSize,
          background_color: this.data.selectedColor,
          watermark_option: this.data.watermarkEnabled ? '添加' : '不添加',
          watermark_text: this.data.watermarkText,
          language: 'zh'
        },
        header: {
          'openid': openid
        },
        success: (res) => {
          const data = JSON.parse(res.data)
          if (data.success) {
            const result = data.data
            // 确保URL拼接正确，避免多余的斜杠
            const safeUrl = (path) => {
              if (!path) return '';
              // 如果路径以/开头，移除开头的斜杠以避免双斜杠
              if (path.startsWith('/')) {
                return path.substring(1);
              }
              return path;
            };
            
            const images = [
              { label: '原图', url: apiUrl + safeUrl(result.original), type: 'original' },
              { label: '标准照', url: apiUrl + safeUrl(result.standard), type: 'standard' },
              { label: '高清照', url: apiUrl + safeUrl(result.hd), type: 'hd' },
              { label: '透明背景', url: apiUrl + safeUrl(result.transparent_standard), type: 'transparent' },
              { label: '排版照', url: apiUrl + safeUrl(result.layout), type: 'layout' }
            ]
            
            // 计算删除日期并格式化
            const deleteDate = new Date(result.metadata.delete_at);
            const formattedDeleteDate = `${deleteDate.getFullYear()}年${deleteDate.getMonth() + 1}月${deleteDate.getDate()}日`;
            
            // 保存到本地画廊
            let gallery = wx.getStorageSync('photoGallery') || [];
            
            // 先删除旧的同尺寸同背景色图片
            gallery = gallery.filter(item => 
                !(item.size === result.metadata.size && 
                  item.color === result.metadata.background_color)
            );
            
            const newPhoto = {
                id: Date.now(),
                thumbnail: result.standard,
                original: result.original,
                standard: result.standard,
                hd: result.hd,
                transparent: result.transparent_standard,
                layout: result.layout,
                date: new Date().toLocaleDateString('zh-CN'),
                size: result.metadata.size,
                color: result.metadata.background_color,
                created_at: result.metadata.created_at,
                delete_at: result.metadata.delete_at
            };
            
            // 添加新图片到开头
            gallery.unshift(newPhoto);
            wx.setStorageSync('photoGallery', gallery);
            wx.showToast({
                title: '已保存到画廊',
                icon: 'success'
            });
            
            wx.setStorageSync('photoGallery', gallery);
            
            this.setData({
              resultImages: images,
              deleteAt: formattedDeleteDate
            })
            
            wx.showToast({
              title: `照片将于${formattedDeleteDate}自动删除`,
              icon: 'none',
              duration: 3000
            })
          } else {
            wx.showToast({
              title: data.message || '处理失败',
              icon: 'none'
            })
          }
        },
        fail: () => {
          wx.showToast({
            title: '上传失败，请重试',
            icon: 'none'
          })
        },
        complete: () => {
          this.setData({ isProcessing: false })
        }
      })

      // 监听上传进度
      uploadTask.onProgressUpdate((res) => {
        console.log('上传进度', res.progress)
      })

    } catch (error) {
      console.error('处理图片失败:', error)
      wx.showToast({
        title: '处理失败，请重试',
        icon: 'none'
      })
      this.setData({ isProcessing: false })
    }
  },

  downloadImage(e) {
    const { url } = e.currentTarget.dataset
    
    wx.downloadFile({
      url: url,
      success: (res) => {
        if (res.statusCode === 200) {
          wx.saveImageToPhotosAlbum({
            filePath: res.tempFilePath,
            success: () => {
              wx.showToast({
                title: '保存成功',
                icon: 'success'
              })
            },
            fail: () => {
              wx.showToast({
                title: '保存失败，请检查权限',
                icon: 'none'
              })
            }
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '下载失败',
          icon: 'none'
        })
      }
    })
  }
})